package com.ruoyi.common.cs.component;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.enums.MultiTenantEnums;
import com.ruoyi.common.core.event.DefaultMuiltTenantListener;
import com.ruoyi.common.core.event.MultiTenantEvent;
import com.ruoyi.common.core.event.SysTenantDTO;
import com.ruoyi.common.cs.cache.ElasticsearchTemplateHoulder;
import com.ruoyi.common.cs.domain.EsClientInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;

@Component
@Slf4j
public class ElasticsearchTemplateManager extends DefaultMuiltTenantListener {

    @Override
    public void onApplicationEvent(MultiTenantEvent event) {
        super.onApplicationEvent(event);
        final MultiTenantEnums multiTenantEnums = event.getMultiTenantEnums();
        SysTenantDTO sysTenantDTO = (SysTenantDTO)event.getSource();
        String esDataSource = sysTenantDTO.getEsDataSource();
        EsClientInfo esClientInfo = JSON.parseObject(esDataSource, EsClientInfo.class);
        switch (multiTenantEnums) {
            case INSERT:
                ElasticsearchTemplateHoulder.refreshTemplate(event.getTenantId(),createElasticsearchRestTemplate(esClientInfo));
                break;
            case UPDATE:
                ElasticsearchTemplateHoulder.refreshTemplate(event.getTenantId(),createElasticsearchRestTemplate(esClientInfo));
                break;
            default:
                break;
        }
    }


    public ElasticsearchRestTemplate createElasticsearchRestTemplate(EsClientInfo esClientInfo ) {
        List<HttpHost> httpHosts = esClientInfo.getHttpHosts();
        InetSocketAddress[] inetSocketAddresses = new InetSocketAddress[httpHosts.size()];
        for (int i=0;i<httpHosts.size() ; i++) {
            inetSocketAddresses[i] = new InetSocketAddress(httpHosts.get(i).getHostName(),httpHosts.get(i).getPort());
        }
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(inetSocketAddresses)
                .withConnectTimeout(Duration.ofMillis(esClientInfo.getConnectTimeoutMillis()))
                .withSocketTimeout(Duration.ofMillis(esClientInfo.getSocketTimeoutMillis()))
                .withBasicAuth(esClientInfo.getUserName(), esClientInfo.getPassword())
                .build();
        return new ElasticsearchRestTemplate(RestClients.create(clientConfiguration).rest());
    }


}
